<script setup lang="ts">
import { h, onMounted, ref, watch } from 'vue';
import type {
  DataTableColumns,
  DrawerPlacement,
  FormInst,
  FormRules,
  UploadCustomRequestOptions,
  UploadFileInfo
} from 'naive-ui';
import { NButton, NImage, useDialog, useMessage } from 'naive-ui';
import {
  commonImageFile,
  deleteCase,
  getCaseInfoList,
  insertCaseInfo,
  msgCheckAction,
  updateCaseInfo
} from '@/service/api';
import { localStg } from '@/utils/storage';

const message = useMessage();

const caseFormRef = ref<HTMLElement & FormInst>();

const memberRules: FormRules = {
  contractName: {
    required: true,
    message: '请输入合同名称',
    trigger: 'blur'
  },
  contractCode: {
    required: true,
    message: '请输入合同编号',
    trigger: 'blur'
  },
  contractAmount: {
    required: true,
    message: '请输入合同金额',
    trigger: 'blur'
  },
  signTime: {
    required: true,
    message: '请选择合同签订时间',
    trigger: 'input'
  },
  buyContent: {
    required: true,
    message: '请输入采购内容',
    trigger: 'blur'
  },
  contractBuyer: {
    required: true,
    message: '请输入买方',
    trigger: 'blur'
  },
  sellerPhone: {
    required: true,
    message: '请输入买方联系方式',
    trigger: 'blur'
  },
  contractSeller: {
    required: true,
    message: '请输入卖方',
    trigger: 'blur'
  }
};

const active = ref(false);

const placement = ref<DrawerPlacement>('right');

const contractImage = ref<UploadFileInfo[]>([]);

const caseForm = ref({
  id: undefined,
  buyContent: undefined,
  contractName: undefined,
  contractCode: undefined,
  contractAmount: undefined,
  signTime: undefined,
  contractBuyer: undefined,
  contractSeller: undefined,
  sellerPhone: undefined,
  remark: undefined,
  contractPicName: undefined, // 合同图片名称
  contractPicPath: undefined // 合同图片地址
});

// 新建
const activate = (place: DrawerPlacement) => {
  active.value = true;
  caseForm.value = {
    id: undefined,
    buyContent: undefined,
    contractName: undefined,
    contractCode: undefined,
    contractAmount: undefined,
    signTime: undefined,
    contractBuyer: undefined,
    contractSeller: undefined,
    sellerPhone: undefined,
    remark: undefined,
    contractPicName: undefined, // 合同图片名称
    contractPicPath: undefined // 合同图片地址
  };
  contractImage.value = [];
  placement.value = place;
};

const emit = defineEmits(['refresh']);

const props = defineProps({
  fileData: {
    type: Array,
    default: () => []
  },
  thirdParentId: {
    type: Number,
    default: 0
  }
});

watch(
  () => props.thirdParentId,
  newValue => {
    if (newValue) {
      getList();
    }
  }
);

const dataList = ref([]);

const formData = ref({
  pageNum: 1,
  pageSize: 10
});

const pageCount = ref<number>();

const { VITE_OTHER_SERVICE_BASE_URL } = import.meta.env;
const otherUrl: any = JSON.parse(VITE_OTHER_SERVICE_BASE_URL);
const imgUrl: any = otherUrl.imgUrl;

const fileList = ref([]);

const dialog = useDialog();

// 确定点击提交事件
async function handleSubmitMember() {
  await caseFormRef.value?.validate(async errors => {
    if (!errors) {
      const checkParams: any = {
        moduleValue: localStg.get('moduleId') || 1,
        keyword: `${caseForm.value.contractName},${caseForm.value.contractCode},${caseForm.value.contractAmount},${caseForm.value.buyContent},${caseForm.value.contractBuyer},${caseForm.value.sellerPhone},${caseForm.value.contractSeller},${caseForm.value.remark}`
      };

      const { data: checkData, error: checkError } = await msgCheckAction(checkParams);
      if (!checkError) {
        if (checkData && checkData.length > 0) {
          dialog.error({
            title: '温馨提示',
            content: `案例信息中包含以下敏感词：\n${checkData.join('，')}`,
            style: 'white-space: pre-line;',
            positiveText: '确认'
          });
          return;
        }
      }

      const tmp = { ...caseForm.value, folderId: props.thirdParentId };
      console.log(tmp);
      const api = tmp.id ? updateCaseInfo : insertCaseInfo;
      const { data, error } = await api(tmp);
      if (!error) {
        active.value = false;
        window.$message?.success('操作成功');
        getList();
      }
    }
  });
}

function closeDrawer() {
  fileList.value = [];
}

const tableLoading = ref(false);

// 获取案例信息
async function getList() {
  tableLoading.value = true;
  const { data, error } = await getCaseInfoList({
    ...formData.value,
    folderId: props.thirdParentId
  });
  if (!error) {
    dataList.value = data?.list;
    pageCount.value = data?.pages;
    tableLoading.value = false;
  }
}

function handleDelete(item: any) {
  dialog.info({
    title: '删除案例',
    content: '请问是否确认删除该案例？',
    positiveText: '确定',
    negativeText: '返回',
    onPositiveClick: async () => {
      const { data, error } = await deleteCase({ ids: item.id });
      if (!error) {
        message.success('已删除');
        getList();
      }
    },
    onNegativeClick: () => {
      message.warning('已取消');
    }
  });
}

// 编辑
function handleEdit(row: any) {
  active.value = true;
  contractImage.value = [];
  caseForm.value = JSON.parse(JSON.stringify(row));
  if (caseForm.value.contractPicPath) {
    const picData = {
      id: caseForm.value.id,
      name: caseForm.value.contractPicName,
      status: 'finished',
      url: imgUrl + caseForm.value.contractPicPath
    };
    contractImage.value.push(picData);
  }
}
// 删除图片
function removeImgClick(
  options: {
    file: UploadFileInfo;
    fileList: Array<UploadFileInfo>;
  },
  name: any,
  path: any
) {
  fileList.value = [];
  caseForm.value[name] = undefined;
  caseForm.value[path] = undefined;
  console.log(caseForm.value);
}

// 自定义上传图片
const customImageRequest = async ({ file, onFinish }: UploadCustomRequestOptions, name: any, path: any) => {
  console.log(file);
  const formData = new FormData();
  if (file.status == 'pending') {
    formData.append('uploadFiles', file.file as Blob);
  }
  const { data, error } = await commonImageFile(formData);
  if (!error) {
    console.log(data[0]);
    caseForm.value[name] = data[0].fileCname;
    caseForm.value[path] = data[0].filePath;
    onFinish();
    console.log(caseForm.value);
  }
};

onMounted(() => {
  getList();
});

function createColumns(): DataTableColumns {
  return [
    {
      title: '序号',
      align: 'center',
      key: 'key',
      render: (_, index) => {
        return `${(formData.value.pageNum - 1) * formData.value.pageSize + index + 1}`;
      }
    },
    {
      title: '合同名称',
      key: 'contractName',
      align: 'center',
      ellipsis: {
        tooltip: true
      },
      width: '160'
    },
    {
      title: '合同编号',
      key: 'contractCode',
      align: 'center'
    },
    {
      title: '合同签订时间',
      key: 'signTime',
      align: 'center',
      width: '180'
    },
    {
      title: '采购内容',
      key: 'buyContent',
      align: 'center',
      ellipsis: {
        tooltip: true
      }
    },
    {
      title: '合同金额（万）',
      key: 'contractAmount',
      align: 'center',
      width: '150'
    },
    {
      title: '合同卖方',
      key: 'contractSeller',
      align: 'center',
      ellipsis: {
        tooltip: true
      }
    },
    {
      title: '合同买方',
      key: 'contractBuyer',
      align: 'center',
      ellipsis: {
        tooltip: true
      }
    },
    {
      title: '合同截图',
      key: 'contractPicPath',
      align: 'center',
      render(row: any) {
        return [
          h(NImage, {
            width: 50,
            src: imgUrl + row.contractPicPath
          })
        ];
      }
    },
    {
      title: '操作',
      key: 'actions',
      align: 'center',
      width: '180',
      render(row: any) {
        return [
          h(
            NButton,
            {
              type: 'info',
              strong: true,
              tertiary: true,
              style: 'margin-right:10px',
              onClick: () => handleEdit(row)
            },
            { default: () => '编辑' }
          ),
          h(
            NButton,
            {
              type: 'error',
              strong: true,
              tertiary: true,
              onClick: () => handleDelete(row)
            },
            { default: () => '删除' }
          )
        ];
      }
    }
  ];
}
const columns: any = createColumns();
</script>

<template>
  <div class="w-full">
    <!-- 新增案例 -->
    <img
      class="upload"
      src="@/assets/bid-materials/addCase.png"
      alt=""
      style="width: 120px"
      @click="activate('right')"
    />
    <div class="table-area">
      <NDataTable
        striped
        size="small"
        :loading="tableLoading"
        :columns="columns"
        :data="dataList"
        :bordered="false"
        :max-height="600"
        style="font-size: 15px; color: #666666"
      />
      <NPagination
        v-model:page="formData.pageNum"
        v-model:page-size="formData.pageSize"
        size="medium"
        style="float: right; position: absolute; top: 810px; right: 80px"
        :page-count="pageCount"
        @update:page="getList"
      />
    </div>
  </div>
  <NDrawer v-model:show="active" :width="800" :placement="placement" :mask-closable="false">
    <NDrawerContent title="案例信息" closable>
      <template #header>案例信息</template>
      <NForm
        ref="caseFormRef"
        :model="caseForm"
        :rules="memberRules"
        require-mark-placement="left"
        label-placement="left"
      >
        <NGrid :cols="24" :x-gap="24">
          <NFormItemGi :span="20" label="合同名称" path="contractName" :label-width="160">
            <NInput v-model:value="caseForm.contractName" placeholder="请输入" />
          </NFormItemGi>
          <NFormItemGi :span="12" label="合同编号" path="contractCode" :label-width="160">
            <NInput v-model:value="caseForm.contractCode" placeholder="请输入" />
          </NFormItemGi>
          <NFormItemGi :span="8" label="合同金额" path="contractAmount">
            <NInput v-model:value="caseForm.contractAmount" placeholder="请输入" />
          </NFormItemGi>
          <NFormItemGi :span="20" label="合同签订时间" path="signTime" :label-width="160">
            <NDatePicker
              v-model:formatted-value="caseForm.signTime"
              style="width: 280px"
              value-format="yyyy-MM-dd HH:mm:ss"
              type="datetime"
              clearable
            />
          </NFormItemGi>
          <NFormItemGi :span="20" label="采购内容" path="buyContent" :label-width="160">
            <NInput v-model:value="caseForm.buyContent" placeholder="请输入" />
          </NFormItemGi>
          <NFormItemGi :span="12" label="合同买方" path="contractBuyer" :label-width="160">
            <NInput v-model:value="caseForm.contractBuyer" placeholder="请输入" />
          </NFormItemGi>
          <NFormItemGi :span="8" label="联系方式" path="sellerPhone">
            <NInput v-model:value="caseForm.sellerPhone" placeholder="请输入" />
          </NFormItemGi>
          <NFormItemGi :span="20" label="合同卖方" path="contractSeller" :label-width="160">
            <NInput v-model:value="caseForm.contractSeller" placeholder="请输入" />
          </NFormItemGi>
          <NFormItemGi :span="20" label="备注" path="remark" :label-width="160">
            <NInput v-model:value="caseForm.remark" placeholder="请输入" />
          </NFormItemGi>
          <NFormItemGi :span="22" label="合同截图" :label-width="160">
            <NUpload
              accept=".jpg, .png"
              :multiple="false"
              :default-file-list="contractImage"
              list-type="image-card"
              :max="1"
              :custom-request="
                $event => {
                  customImageRequest($event, 'contractPicName', 'contractPicPath');
                }
              "
              @remove="
                $event => {
                  removeImgClick($event, 'contractPicName', 'contractPicPath');
                }
              "
            >
              <span>合同截图</span>
            </NUpload>
          </NFormItemGi>
        </NGrid>
      </NForm>
      <template #footer>
        <NButton style="width: 110px; height: 40px; margin-right: 20px" @click="() => (active = false)">取 消</NButton>
        <NButton type="primary" style="width: 110px; height: 40px" @click="handleSubmitMember">确 定</NButton>
      </template>
    </NDrawerContent>
  </NDrawer>
</template>

<style scoped lang="scss">
.table-area {
  margin-top: 15px;
  margin-left: 35px;
  width: 1485px;
  height: 400px;
  :deep(.n-data-table .n-data-table-th) {
    background-color: #f2f0ff;
    height: 60px;
    color: #333333;
    font-size: 18px;
  }
}
.upload {
  float: right;
  margin-bottom: 15px;
  margin-right: 79px;
  &:hover {
    cursor: pointer;
  }
}
</style>
